import store from '@/store'
import storage from '@/utils/storage'
import { createRouter, createWebHashHistory } from 'vue-router'

import NProgress from 'nprogress'

const modules = import.meta.glob(`@/views/**/**.vue`, { eager: true })
const moduleMap = {}

Object.keys(modules).forEach((path) => {
  const module = modules[path]
  path = path.substring(path.indexOf('/views') + 6)
  moduleMap[path] = module

  if (path.endsWith('index.vue')) {
    path = path.substring(0, path.length - 10)
    if (path) {
      moduleMap[path] = module
    }
  }
})

export const routes = [
  {
    name: '登录',
    path: '/login',
    component: () => import('@/views/login'),
    meta: {
      searchable: false,
    },
  },
  {
    name: '申请授权',
    path: '/oauth2/authorize',
    component: () => import('@/views/oauth2/Authorize'),
    props: (route) => ({
      client_id: route.query.client_id,
      response_type: route.query.response_type,
      redirect_uri: route.query.redirect_uri,
      scope: route.query.scope,
      state: route.query.state,
      code_challenge: route.query.code_challenge,
      code_challenge_method: route.query.code_challenge_method,
    }),
    meta: {
      searchable: false,
    },
  },
  {
    path: '/',
    name: '二级路由',
    component: () => import('@/layout/index'),
    meta: {
      searchable: false,
    },
    children: [
      {
        name: '403',
        path: '/403',
        component: () => import('@/views/error/403'),
        meta: {
          searchable: false,
        },
      },
      {
        name: '404',
        path: '/404',
        component: () => import('@/views/error/404'),
        meta: {
          searchable: false,
        },
      },
      {
        name: '个人信息',
        path: '/loginUser/info',
        component: () => import('@/views/loginUser/info'),
      },
      {
        name: '修改密码',
        path: '/loginUser/modifyPassword',
        component: () => import('@/views/loginUser/modifyPassword'),
      },
      {
        name: '错误日志',
        path: '/errorLog',
        component: () => import('@/views/error/errorLog'),
      },
    ],
  },
  {
    name: '没有找到',
    path: '/:pathMatch(.*)',
    redirect: '/404',
    meta: {
      searchable: false,
    },
  },
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: routes,
  strict: true,
})

NProgress.configure({ showSpinner: false })

const loginIgnore = {
  names: [], //根据路由名称匹配
  paths: ['/login'], //根据路由fullPath匹配
  // 判断路由是否包含在该配置中
  includes(route) {
    return this.names.includes(route.name) || this.paths.includes(route.path)
  },
}

const viewTabIgnore = {
  names: ['二级路由', '404'], //根据路由名称匹配
  paths: [], //根据路由fullPath匹配
  // 判断路由是否包含在该配置中
  includes(route) {
    return this.names.includes(route.name) || this.paths.includes(route.path)
  },
}

// 加载路由守卫
router.beforeEach(async (to, from, next) => {
  if (!NProgress.isStarted()) {
    NProgress.start()
  }

  if (to.path == '/') {
    if (store.getters.indexMenu) {
      next('/index')
    } else {
      store.dispatch('loginUser/gotoLogin')
      next('/login')
    }
    return
  }

  if (loginIgnore.includes(to)) {
    next()
    return
  }

  if (!store.getters.loginUserToken) {
    store.dispatch('loginUser/gotoLogin')
    next('/login')
    return
  }

  if (Object.keys(store.getters.loginUserInfo).length == 0) {
    await store.dispatch('loginUser/getInfo')
  }

  if (!viewTabIgnore.includes(to)) {
    store.commit('viewTab/ADD_VIEWTAB', {
      name: to.name,
      path: to.path,
      query: to.query,
      params: to.params,
    })
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

// 加载路由
export function loadDynamicRoutes(menus) {
  let addRoute = (menu) => {
    if (!menu.menuPage || menu.menuType == 'AUTHORITY') {
      return
    }

    router.addRoute('二级路由', {
      name: menu.menuName,
      path: menu.index ? '/index' : menu.menuPage,
      component: () =>
        moduleMap[menu.menuPage] == null
          ? import('@/views/error/404')
          : new Promise((resolve) => {
              resolve(moduleMap[menu.menuPage])
            }),
      meta: {
        title: menu.menuName,
        show: true,
        keepAlive: menu.keepAlive,
        icon: menu.menuIcon,
      },
    })
  }

  for (let i in menus) {
    let menu = menus[i]
    if (menu.menuType == 'CATALOG') {
      for (let j in menu.children) {
        let child = menu.children[j]
        addRoute(child)
      }
    } else if (menu.menuType == 'MENU') {
      addRoute(menu)
    }
  }
}

export function removeDynamicRoutes() {
  let removeRoute = (menu) => {
    if (!menu.menuPage) {
      return
    }
    router.removeRoute(menu.menuName)
  }

  for (let i in store.getters.menus) {
    let menu = store.getters.menus[i]
    if (menu.menuType == 'CATALOG') {
      for (let j in menu.children) {
        let child = menu.children[j]
        removeRoute(child)
      }
    } else if (menu.menuType == 'MENU') {
      removeRoute(menu)
    }
  }
}

const menus = storage.get('menus')
if (menus && menus.length > 0) {
  loadDynamicRoutes(menus)
}

export default router
